﻿using System;
using System.IO;
using Newtonsoft.Json;

namespace Fetches.Fetch.Utils
{
    public interface IJsonWriteable
    {
    }

    public static class JsonFileHelper
    {
        /// <summary>
        ///     序列化保存到磁盘
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string ToJsonFile(this IJsonWriteable obj, string file)
        {
            var str = JsonConvert.SerializeObject(obj);
            var fullPath = Path.GetFullPath(file);
            var path = Path.GetDirectoryName(fullPath);
            Directory.CreateDirectory(path ?? throw new ArgumentException("文件路径不正确"));
            File.WriteAllText(fullPath, str);
            return fullPath;
        }

        /// <summary>
        ///     加载已保存数据
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static T FromFile<T>(string file)
        {
            return JsonConvert.DeserializeObject<T>(File.ReadAllText(Path.GetFullPath(file)));
        }
    }
}